﻿using FreeSql.Internal.ObjectPool;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PropertyChanged;
using sys_Print.DataAsset;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Linq;
using System.Text;

namespace sys_Print.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    public class ContentTypeViewModel : ViewModelBase
    {
        [DoNotNotify]
        private readonly IFreeSql _fsql;

        public ObservableCollection<ContentType> DataList { get; set; }
        public List<PrintModelType> PrintModelTypes { get; set; }
        public RelayCommand SubmitButtonCommand { get; private set; }
        public RelayCommand AddButtonCommand { get; private set; }
        public RelayCommand RefreshButtonCommand { get; private set; }

        public ContentTypeViewModel()
        {
            // 获取配置好的FreeSql实例
            _fsql = App.FsqlDB;

            SubmitButtonCommand = new RelayCommand(new Action(OnSubmitButton));
            AddButtonCommand = new RelayCommand(new Action(OnAddButton));
            RefreshButtonCommand = new RelayCommand(new Action(OnRefreshButton));

            PrintModelTypes = _fsql.Select<PrintModelType>().Where(a => a.State == true).ToList();

            OnRefreshButton();
        }

        private void OnAddButton()
        {
            DataList.Add(new ContentType()
            {
                ContentModelId = DataList.Count + 1 ,

            });
        }

        private void OnSubmitButton()
        {
            // 获取在 DataGrid 中所做的更改
            var modifiedItems = DataList.Where(item => item.IsChanged);

            using (Object<DbConnection> conn = _fsql.Ado.MasterPool.Get())
            {
                using (DbTransaction transaction = conn.Value.BeginTransaction())
                {
                    try
                    {
                        foreach (ContentType item in modifiedItems)
                        {
                            _fsql.InsertOrUpdate<ContentType>().SetSource(item).WithTransaction(transaction).ExecuteAffrows();

                            // 将更改标记为已提交
                            item.AcceptChanges();
                        }

                        transaction.Commit();
                        HandyControl.Controls.Growl.Info("提交完成！");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        //记录日志，抛出异常（使用全局异常）或者返回自定义数据 
                        throw ex;
                    }
                }
            }
        }

        private void OnRefreshButton()
        {
            List<ContentType> list = _fsql.Select<ContentType>().OrderBy(a => a.ContentModelId).ToList();
            DataList = new ObservableCollection<ContentType>(list);
        }

    }
}
